package com.lambkit.module.cms.web.directive;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.lambkit.module.cms.rpc.model.CmsArticle;
import com.lambkit.web.LambkitControllerContext;
import com.lambkit.web.directive.LambkitDirective;
import com.lambkit.web.directive.LambkitPaginateDirective;
import com.lambkit.web.directive.annotation.JFinalDirective;

/**
 * @author Henry Yang 杨勇 (gismail@foxmail.com)
 * @version 1.0
 * @Package com.lambkit.module.cms.web.directive
 */
@JFinalDirective("articleSearchPage")
public class ArticleSearchPageDirective extends LambkitDirective {

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {

        Controller controller = LambkitControllerContext.get();

        String keyword = controller.getAttr("keyword");
        int page = controller.getAttr("page");
        int pageSize = getParaToInt("pageSize", scope, 10);

        Page<CmsArticle> dataPage = StrKit.notBlank(keyword)
                ? CmsArticle.service().search(page, pageSize, keyword)
                : null;

        if (dataPage != null) {
            scope.setGlobal("articlePage", dataPage);
        }

        //需要页面自行判断 articlePage 是否为空
        renderBody(env, scope, writer);
    }

    @Override
    public boolean hasEnd() {
        return true;
    }


    @JFinalDirective("articleSearchPaginate")
    public static class SearchPaginateDirective extends LambkitPaginateDirective {
        @Override
        protected Page<?> getPage(Env env, Scope scope, Writer writer) {
            return (Page<?>) scope.get("articlePage");
        }
    }
}
